<!-- @author benjamin_5 @date 2022/10/12-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jQuery3.6.1.js"></script>
</head>
<body>
<div class="modal-body form ">
    <!-- 文件上传   -->
    <form id="dialogForm" class="form-horizontal">
        <div class="form-group">
            <label class="control-label">文件:</label>
            <div >
                <input type="file" name="file" id="file" onchange="upload()">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label">上传进度:</label>
            <div >
                <!--进度条-->
                <div id="progress-body">
                    <progress></progress>
                    <div id="progress-bar">0%</div>
                </div>
            </div>
        </div>
    </form>
    <br>
    <a href="download.html" id="a">下载文件</a>

</div>

</body>
    <script>
        // 文件上传
        function upload() {
            var formData = new FormData();
            formData.append("file", $("#file")[0].files[0]);
            $.ajax({
                url : "/file/upload",
                type : "POST",
                data : formData,
                processData : false, // 告诉jQuery不要去处理发送的数据
                contentType : false, // 告诉jQuery不要去设置Content-Type请求头
                success : function(data) {
                    console.log(data);
                },
                xhr : function() {
                    var xhr = $.ajaxSettings.xhr();
                    if (xhr.upload) {
                        //处理进度条的事件
                        xhr.upload.addEventListener("progress", progressHandle,
                            false);
                        //加载完成的事件
                        xhr.addEventListener("load", uploadSuccess, false);
                        //加载出错的事件
                        xhr.addEventListener("error", uploadFail, false);
                        return xhr;
                    }
                }
            });
        }
        //进度条更新
        function progressHandle(e) {
            $('#progress-body progress').attr({
                value : e.loaded,
                max : e.total
            });
            var percent = (e.loaded / e.total * 100).toFixed(2);
            $('#progress-body #progress-bar').html(percent + "%");
        };
        //上传完成处理函数
        function uploadSuccess(e) {
            alert("上传完成");
        };
        //上传出错处理函数
        function uploadFail(e) {
            alert("上传失败");
        };
    </script>
</html>